/**
 * Created with PyCharm.
 * User: Amanda
 * Date: 14-5-26
 * Time: 下午4:40
 * To change this template use File | Settings | File Templates.
 */

dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.map");
dojo.require("esri.graphic");
dojo.require("esri.layers.agstiled");
dojo.require("esri.toolbars.draw");
dojo.require("dijit.dijit"); // optimize: load dijit layer
dojo.require("esri.undoManager");
dojo.provide("myModules.customoperation");
dojo.require("esri.tasks.geometry");

var mymap,toolbar,reExtent,dotList,undoManager,resizeTimer,componentType,geometryService;

var mapColor = {
    production:{
        solidColor:[145,187,53],
        fillColor:[0,187,255,255],
        fill_color:[0,187,255,64]
    },
    storage:{
        solidColor:[145,197,53],
        fillColor:[145,197,53,255],
        fill_color:[145,197,53,64]
    }
}
//初始化地图
function init(){
    undoManager = new esri.UndoManager();
    mymap = new esri.Map("map");
    toolbar = new esri.toolbars.Draw(mymap);


    //加载天地图
    dojo.declare("TianDiTiledMapServiceLayer", esri.layers.TiledMapServiceLayer, {
        constructor: function() {
            this.spatialReference = new esri.SpatialReference({ wkid:4326 });
            this.initialExtent = (this.fullExtent =
                new esri.geometry.Extent(-180.0, -90.0, 180.0, 90.0, this.spatialReference));

            this.tileInfo = new esri.layers.TileInfo({
                "rows" : 256,
                "cols" : 256,
                "compressionQuality" : 0,
                "origin" : { "x" : -180,"y" : 90},
                "spatialReference" : {"wkid" : 4326},
                "lods" : [
                    {"level" : 0, "resolution" : 0.703125, "scale" : 295497593.05875},
                    {"level" : 1, "resolution" : 0.3515625, "scale" : 147748796.529375},
                    {"level" : 2, "resolution" : 0.17578125, "scale" : 73874398.264688},
                    {"level" : 3, "resolution" : 0.087890625, "scale" : 36937199.132344},
                    {"level" : 4, "resolution" : 0.0439453125, "scale" : 18468599.566172},
                    {"level" : 5, "resolution" : 0.02197265625, "scale" : 9234299.783086},
                    {"level" : 6, "resolution" : 0.010986328125, "scale" : 4617149.891543},
                    {"level" : 7, "resolution" : 0.0054931640625, "scale" : 2308574.945771},
                    {"level" : 8, "resolution" : 0.00274658203125, "scale" : 1154287.472886},
                    {"level" : 9, "resolution" : 0.001373291015625, "scale" : 577143.736443},
                    {"level" : 10, "resolution" : 0.0006866455078125, "scale" : 288571.86822143558},
                    {"level" : 11, "resolution" : 0.00034332275390625, "scale" : 144285.93411071779},
                    {"level" : 12, "resolution" : 0.000171661376953125, "scale" : 72142.967055358895},
                    {"level" : 13, "resolution" : 8.58306884765625e-005, "scale" : 36071.483527679447},
                    {"level" : 14, "resolution" : 4.291534423828125e-005, "scale" : 18035.741763839724},
                    {"level" : 15, "resolution" : 2.1457672119140625e-005, "scale" : 9017.8708819198619},
                    {"level" : 16, "resolution" : 1.0728836059570313e-005, "scale" : 4508.9354409599309},
                    {"level" : 17, "resolution" : 5.3644180297851563e-006, "scale" : 2254.4677204799655}]
            });
            this.loaded = true;
            this.onLoad(this);
        },
        getTileUrl: function(level, row, col) {
            var levelMap = "";
            if(level<10){
                levelMap = "A0512_EMap";
            }else if(level<12){
                levelMap = "B0627_EMap1112";
            }else if(level<18){
                levelMap = "siwei0608";
            }
            return "http://t1.tianditu.cn/DataServer?T=vec_c&"+levelMap+"&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
        }
    });
    //文字标注
    dojo.declare("TianDiBiaoZhuMapServiceLayer", TianDiTiledMapServiceLayer, {
        getTileUrl: function(level, row, col) {
            return "http://t1.tianditu.cn/DataServer?T=cva_c&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
        }
    });
    //影像地图
    dojo.declare("TianDiYXMapServiceLayer", TianDiTiledMapServiceLayer, {
        getTileUrl: function(level, row, col) {//wmts
            return "http://t1.tianditu.cn/DataServer?T=img_c&X=" + col + "&Y=" + row + "&L=" + (level*1+1);
        }
    });

    dojo.declare("myModules.customoperation.Add", esri.OperationBase, {
        label: "Add Graphic",
        constructor: function ( /*graphicsLayer, addedGraphic*/ params) {
            params = params || {};
            if (!params.graphicsLayer) {
                console.error("graphicsLayer is not provided");
                return;
            }
            this.graphicsLayer = params.graphicsLayer;

            if (!params.addedGraphic) {
                console.error("no graphics provided");
                return;
            }
            this._addedGraphic = params.addedGraphic;
        },

        performUndo: function () {
            this.graphicsLayer.remove(this._addedGraphic);
        },

        performRedo: function () {
            this.graphicsLayer.add(this._addedGraphic);
        }
    });

    dojo.connect(toolbar, "onDrawEnd", function(geometry){
        toolbar.deactivate();
        var symbol = new esri.symbol.SimpleFillSymbol(
            esri.symbol.SimpleFillSymbol.STYLE_SOLID,
            new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                new dojo.Color(mapColor.production.solidColor), 2),
            new dojo.Color(mapColor.production.fillColor)
        );

        var graphic = new esri.Graphic(geometry, symbol);
        var operation = new myModules.customoperation.Add({
            graphicsLayer: mymap.graphics,
            addedGraphic: graphic
        });

        undoManager.add(operation);
        mymap.graphics.add(graphic);

        var dotList;
        
        var values = JSON.stringify(graphic.geometry.rings[0]);
        var centerPoint=graphic.geometry.getExtent().getCenter();
        var center = "["+centerPoint.x +","+centerPoint.y +"]"

        //给赋地图值
        $('#center').val(center);
        $('#valuePolygon').val(values);
    });

    mymap.resize();
    mymap.reposition();
    //加载天地图结束
    dojo.connect(mymap, 'onLoad', function(theMap) {
        dojo.connect(dijit.byId('map'), 'resize', map,map.resize);
    });
    // dojo.connect(mymap, "onLoad", showPosition);
    dojo.connect(mymap, "onExtentChange", showExtent);
    //configure map pan animation to be slower
    esri.config.defaults.map.panDuration = 1000; //time in milliseconds; default panDuration:250
    esri.config.defaults.map.panRate = 50; //refresh rate of zoom animation; default panRate:25
    mymap.resize();
    mymap.reposition();
    mymap.addLayer(new TianDiTiledMapServiceLayer());
    mymap.addLayer(new TianDiYXMapServiceLayer());
    mymap.addLayer(new TianDiBiaoZhuMapServiceLayer());


    
    loadParkRange(); // 加载园区地图边界
    loadCompanyRange(); // 加载企业地图边界

    if(p_extent)
        reExtent = new esri.geometry.Extent({
            "xmin":p_extent.XMin,
            "ymin":p_extent.YMin,
            "xmax":p_extent.XMax,
            "ymax":p_extent.YMax,
            "spatialReference":{
                "wkid":54032
            }
        });
    
    mymap.setExtent(reExtent);

    var mapData = $('#_mapData').html();
    if(mapData == '') return false;
    mapData = eval("("+ mapData +")");

    for(var i=0; i<mapData.length; i++){
        var _obj = mapData[i];
        var _graphData = {
            name : _obj.name,
            color: mapColor[ _obj.name ]
        }

        ;(function(_graphData, typeName){
            console.log(_obj.url)
            console.log("-----------")
            $.get(_obj.url,function(data){
                _graphData.mapData = data || [];

                for(var j=0; j<_graphData.mapData.length; j++){
                    var _ItemOptions = {
                        points:eval('('+ _graphData.mapData[j].group.points +')'),
                        color:_graphData.color,
                        name:_graphData.name,
                        structure:_graphData.mapData[j].structure.split(','),
                        header:_graphData.mapData[j].header.split(','),
                        infoData:_graphData.mapData[j].data,
                        title:_graphData.mapData[j].title,
                    }
                    loadCompanyData(_ItemOptions, typeName);
                }

            },'json');

        })(_graphData, _obj.name);
    }

}
dojo.addOnLoad(init);

function showPosition(){
    var _tmpColor = {
        solidColor:[0,187,255],
        fillColor:[0,187,255,255],
        fill_color:[0,187,255,64]
    };

    if(_geoPoints == ''){
        return false;
    }else{
        _geoPoints = JSON.parse(_geoPoints);
    }

    //建设传过来的数据时数组字符串
    var myPolygon = {
        "geometry":{
            "rings":[ _geoPoints ],
            "spatialReference": { "wkid": 102100 }
        },
        "symbol":{
            "color":_tmpColor.fill_color,
            "outline":{
                "color":_tmpColor.fillColor,
                "width":2,
                "type":"esriSLS",
                "style":"esriSLSSolid"
            },
            "type":"esriSFS",
            "style":"esriSFSSolid"
        }
    };

    var gra = new esri.Graphic(myPolygon);
    mymap.graphics.add(gra);
}

function showExtent(extent) {
    $("#info").attr("XMin",extent.xmin.toFixed(2) );
    $("#info").attr("YMin",extent.ymin.toFixed(2) );
    $("#info").attr("XMax",extent.xmax.toFixed(2) );
    $("#info").attr("YMax",extent.ymax.toFixed(2) );
}

var list_ ;
//加载园区边界
function loadParkRange(){
    var solidColor = [254,236,36],
        fillColor = [102,255,51,255],
        fill_color = [255,255,255,0];
    var rangePolygon = {
        "geometry":{
            "rings":[p_points],
            "spatialReference": { "wkid": 102100 }
        },
        "symbol":{
            "color":fill_color,
            "outline":{
                "color":fillColor,
                "width":4,
                "type":"esriSLS",
                "style":"esriSLSSolid"
            },
            "type":"esriSFS",
            "style":"esriSFSSolid"
        }
    };
    var gra = new esri.Graphic(rangePolygon);

    mymap.graphics.add(gra);
}

//加载企业边界
function loadCompanyRange(){
    var solidColor = [254,236,36],
        fillColor = [255, 52, 179,255],
        fill_color = [255,255,255,0];
    var rangePolygon = {
        "geometry":{
            "rings":[e_points],
            "spatialReference": { "wkid": 102100 }
        },
        "symbol":{
            "color":fill_color,
            "outline":{
                "color":fillColor,
                "width":4,
                "type":"esriSLS",
                "style":"esriSLSSolid"
            },
            "type":"esriSFS",
            "style":"esriSFSSolid"
        }
    };
    var gra = new esri.Graphic(rangePolygon);
    mymap.graphics.add(gra);
}

//加载企业数据
function loadCompanyData(options, type){
    
    var _tmpInfo = $("#mapPopHideArea").clone();

    if(options.infoData.length == 0){
        _tmpInfo.html('暂无数据');
    }else{
        for(var i=0; i<options.header.length; i++){
            var _th = '<th>'+ options.header[i] +'</th>'
            _tmpInfo.find("#_headTr").append( _th );
        }
        for(var i = 0; i < options.infoData.length; i++){
            var _tmp = options.infoData[i];
            var _tr = '<tr>';

            for(var j=0; j<options.structure.length; j++){
                _tr+= '<td>'+ _tmp[ options.structure[j] ] +'</td>'
            }
            _tr+= '</tr>';
            _tmpInfo.find("table tbody").append(_tr);
        }
    }

    var _context = _tmpInfo.html();
    var myPolygon = {
        "geometry":{
            "rings":[options.points],
            "spatialReference": {
                "wkid": 102100
            }
        },
        "attributes":{
            "name":options.name,
            "title": '绿库'
        },
        "symbol":{
            "color":options.color.fill_color,
            "outline":{
                "color":options.color.fillColor,
                "width":2,
                "type":"esriSLS",
                "style":"esriSLSSolid"
            },
            "type":"esriSFS",
            "style":"esriSFSSolid"
        },
        "infoTemplate":{
            "title":options.title ,
            "content":"<div>"+ _context +"</div>"
        }
    };

    // 初始化单元图层对象
    var gra = new esri.Graphic(myPolygon);
    // 获得当前单元图层中心点
    // var centerPoint=gra.geometry.getExtent().getCenter();
    // 先添加单元图层
    mymap.graphics.add(gra);
}

function toSubmitModal(title,type){     // storeCell  storage的内容    开始赋值呈现
    $('#rangeModal').modal({show:true});
    // $('#rangeModal #content').empty().append(content);
    $("#rangeModal #title").empty().append(title);
    $("#storeType").val(type)
    $("#rangeModal #submit").bind('click',function(){
        submitData();
    });
}

function submitData(){
    var doList = $('#valuePolygon').val();
    var center = $('#center').val();
    var arrValue = $('#ids').val().split(',');
    $.ajax({
        url:$.showMapObj.options.dataSubmitURL,
        data:{
            ids:JSON.stringify(arrValue),    //某个storage的id   种类已经知道了
            points:doList, //地图信息
            center:center
        },
        type:'POST',
        dataType:'json',
        success:function(data){
            if(data.success){
                alert(data.success);
                window.location.reload();
            }
            if(data.error){
                alert(data.error);
            }
        }
    })
}

function drowPolygon(name){   //'store'
    toolbar.activate(esri.toolbars.Draw.POLYGON);   //可以画多边形了
    //携带，一个参数
    var info="";
    switch(name){
        case "store":
            info = "开始绘制存储单元边界";
            break;
    }
    infoPop(info);
}

function infoPop(info){
    $("#toast-container").remove();
    var opts = {
        "closeButton": true,
        "debug": false,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "2000",
        "extendedTimeOut": "5000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    toastr.info("", info, opts);
}

